// 用户数据模型示例
import { Collection, ObjectId } from 'mongodb'
import { getDB } from '../config/database.js'

// 用户接口定义
export interface User {
  _id?: ObjectId
  username: string
  email: string
  password: string // 新增：加密后的密码
  role: 'viewer' | 'trader' | 'risk' | 'admin' | 'auditor' // 完善角色类型
  createdAt?: Date
  updatedAt?: Date
}

/**
 * 获取用户集合
 */
export function getUsersCollection(): Collection<User> {
  const db = getDB()
  return db.collection<User>('pcusers')
}

/**
 * 创建新用户
 */
export async function createUser(
  userData: Omit<User, '_id' | 'createdAt' | 'updatedAt'>,
): Promise<User> {
  const collection = await getUsersCollection()
  const now = new Date()

  const user: User = {
    ...userData,
    createdAt: now,
    updatedAt: now,
  }

  const result = await collection.insertOne(user)
  return { ...user, _id: result.insertedId }
}

/**
 * 根据 ID 查找用户
 */
export async function findUserById(id: string): Promise<User | null> {
  const users = getUsersCollection()
  return users.findOne({ _id: new ObjectId(id) })
}

/**
 * 根据用户名查找用户
 */
export async function findUserByUsername(
  username: string,
): Promise<User | null> {
  const users = getUsersCollection()
  return users.findOne({ username })
}

/**
 * 获取所有用户
 */
export async function getAllUsers(): Promise<User[]> {
  const users = getUsersCollection()
  return users.find().toArray()
}

/**
 * 根据邮箱查找用户
 */
export async function findUserByEmail(email: string): Promise<User | null> {
  const collection = await getUsersCollection()
  return collection.findOne({ email })
}
